package com.hospital.wx.service.Impl;

import com.hospital.wx.config.WxMiniConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/*
* 负责管理微信接口调用凭证
 * */
@Service
@Slf4j
public class WxAccessTokenService {
//    private static final Logger logger = LoggerFactory.getLogger(WxAccessTokenService.class);
    private static final String ACCESS_TOKEN_KEY = "wx:access_token";

    @Autowired
    private WxMiniConfig wxMiniConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /*
     * 获取微信小程序接口调用凭证
     */
    public String getAccessToken() {
        // 先从缓存获取
        String accessToken = redisTemplate.opsForValue().get(ACCESS_TOKEN_KEY);
        if (accessToken != null && !accessToken.isEmpty()) {
            return accessToken;
        }

        // 缓存没有，则请求微信接口
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + wxMiniConfig.getAppId() +
                "&secret=" + wxMiniConfig.getAppSecret();

        ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);

        if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
            Map<String, Object> body = response.getBody();

            if (body.containsKey("access_token")) {
                accessToken = (String) body.get("access_token");
                // 缓存token，过期时间设为7000秒（微信token有效期7200秒）
                redisTemplate.opsForValue().set(ACCESS_TOKEN_KEY, accessToken, 7000, TimeUnit.SECONDS);
                return accessToken;
            } else {
                log.error("获取微信access_token失败: {}", body);
                throw new RuntimeException("获取微信access_token失败: " + body.get("errmsg"));
            }
        } else {
            log.error("获取微信access_token请求失败: {}", response);
            throw new RuntimeException("获取微信access_token请求失败");
        }
    }

}
